package com.qyxx.platform.sysmng.memo.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.qyxx.platform.common.orm.Page;
import com.qyxx.platform.common.orm.PropertyFilter;
import com.qyxx.platform.dwr.reverseajax.Comet;
import com.qyxx.platform.sysmng.accountmng.dao.UserDao;
import com.qyxx.platform.sysmng.memo.dao.MemoDao;
import com.qyxx.platform.sysmng.memo.dao.MemoToUserDao;
import com.qyxx.platform.sysmng.memo.entity.Memo;
import com.qyxx.platform.sysmng.memo.entity.MemoToUser;
@Component
@Transactional
public class MemoManager {
	
	private static final String FIND_CURRENTUSER_MEMOS = "select new Memo(b,a) from MemoToUser a inner join a.memo b where b.status = ? and a.userId = ?";
	private static final String FIND_MEMO_BY_MEMOTOUSERID = "select new Memo(b,a) from MemoToUser a inner join a.memo b where a.id = ?";
	private static final String FIND_MEMO_BY_STATUS = "select new Memo(b,a) from MemoToUser a inner join a.memo b where b.status = ? and a.status = ?";
	private static final String FIND_EXPIRE_MEMO_BY_USERID = "select new Memo(b,a) from MemoToUser a inner join a.memo b where b.status = ? and a.status = ? and a.userId = ?";
	private MemoDao memoDao;
	private MemoToUserDao memoToUserDao;
	
	private UserDao userDao;
	
	/**
	 * @param userDao
	 */
	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
	@Autowired
	public void setMemoToUserDao(MemoToUserDao memoToUserDao) {
		this.memoToUserDao = memoToUserDao;
	}

	@Autowired
	public void setMemoDao(MemoDao memoDao) {
		this.memoDao = memoDao;
	}

	/**
	 * 保存一条备忘录
	 * 
	 * @param memo
	 * @param userId
	 */
	public void saveMemo(Memo memo, Long userId) {
		//修改一条备忘录
		if(memo.getId() != null) {
			memo.setLastUpdateUser(userId);
			memo.setLastUpdateTime(new Date());
		} else {
			//新增一条备忘录
			memo.setCreateUser(userId);
			memo.setCreateTime(new Date());
		}
		memoDao.save(memo);
		memoToUserDao.deleteByMemoId(memo.getId());
    	String ids = memo.getMemoToUserIds();
    	if (StringUtils.isNotBlank(ids)) {
			String[] id = ids.split(",");
			if(id != null) {
				for (String tid : id) {
					Long mToUserId = Long.parseLong(tid);
					MemoToUser mtu = new MemoToUser();
			    	mtu.setMemo(memo);
			    	mtu.setUserId(mToUserId);
			    	mtu.setStatus("0");
			    	memoToUserDao.save(mtu);
				}
			}
		}
	}

	/**
	 * 保存一条备忘录
	 * 
	 * @param entity
	 * @param userId
	 */
	@Transactional(readOnly = true)
	public Page<Memo> findMemoList(Page<Memo> page,
			List<PropertyFilter> filters) {
		return preHandlePage(memoDao.findPage(page, filters));
	}
	
	/**
	  * 根据id查找一条备忘录
	  * 
	  * @param id
	  */
	public Memo findById(Long id){
		Memo memo = memoDao.get(id);
		List<MemoToUser> mtus = memo.getMemoToUserList();
		if (mtus != null && !mtus.isEmpty()) {
			boolean mark = false;
			StringBuilder sb = new StringBuilder();
			for (MemoToUser mtu : mtus) {
				if(mark) {
					sb.append(",");
				} else {
					mark = true;
				}
				sb.append(mtu.getUserId());
			}
			memo.setMemoToUserIds(sb.toString());
		}
		return memo;
	}
	
	/**
	 * 删除通知，先要删除用户备忘录关系表中的关系
	 * 
	 * @param ids
	 */
	public void deleteMemos(Long[] ids) {
		// 查询出被删相关用户，推送备忘录被删消息
		List<MemoToUser> memoToUserList = new ArrayList<MemoToUser>();
		if(ids != null) {
			List<MemoToUser> list = findMemoToUserBy(ids);
			if(list != null) {
				for(MemoToUser memoToUser : list) {
					if(MemoToUser.STATUS_1.equals(memoToUser.getStatus())) {
						MemoToUser memoToUser_ = new MemoToUser();
						memoToUser_.setId(memoToUser.getId());
						memoToUser_.setUserId(memoToUser.getUserId());
						Memo memo = new Memo();
						memo.setId(memoToUser.getMemo().getId());
						memo.setTitle(memoToUser.getMemo().getTitle());
						memoToUser_.setMemo(memo);
						memoToUserList.add(memoToUser_); // 筛选出正在提醒的备忘录用户关系
					}
				}
			}
			for(Long id : ids) {
				// 删除与用户的关系
				memoToUserDao.deleteByMemoId(id);
				// 删除通知
				memoDao.delete(id);
			}
		}
		Comet.push(memoToUserList); // 推送备忘录用户关系被删
	}
	
	/**
	 * 根据备忘录id查找备忘录用户关系
	 * 
	 * @param ids
	 * @return memoToUserList
	 */
	public List<MemoToUser> findMemoToUserBy(Long[] ids) {
		List<MemoToUser> memoToUserList = new ArrayList<MemoToUser>();
		if(ids != null) {
			for(Long id : ids) {
				memoToUserList.addAll(memoToUserDao.findBy("memo.id", id));
			}
		}
		return memoToUserList;
	}

	/**
	 * 修改备忘录状态，服务于撤销发布与发布
	 * 
	 * @param id
	 * @param status
	 * @param userId
	 * @return memoId
	 */
	public Long updateStatus(Long id, String status, Long userId) {
		// TODO Auto-generated method stub
		Memo newMemo = memoDao.get(id);
		List<MemoToUser> memoToUserList = new ArrayList<MemoToUser>();
		if(Memo.STATUS_0.equals(status)) { // 撤销发布后将备忘录用户关系表的提醒状态改为等待提醒
			List<MemoToUser> list = memoToUserDao.findBy("memo", newMemo);
			if(list != null) {
				for(MemoToUser memoToUser : list) {
					if(MemoToUser.STATUS_1.equals(memoToUser.getStatus())) {
						MemoToUser memoToUser_ = new MemoToUser();
						memoToUser_.setId(memoToUser.getId());
						memoToUser_.setUserId(memoToUser.getUserId());
						Memo memo = new Memo();
						memo.setId(memoToUser.getMemo().getId());
						memo.setTitle(memoToUser.getMemo().getTitle());
						memoToUser_.setMemo(memo);
						memoToUserList.add(memoToUser_); // 筛选出正在提醒的备忘录用户关系
					}
					memoToUser.setStatus(MemoToUser.STATUS_0);
				}
			}
		}
		newMemo.setLastUpdateUser(userId);
		newMemo.setLastUpdateTime(new Date());
		newMemo.setStatus(status);
		Comet.push(memoToUserList); // 推送备忘录用户关系被删
		return newMemo.getId();
	}
	
	/**
	 * 分页查询用户被共享的备忘录
	 * 
	 * @param page
	 * @param userId
	 * @param filters
	 */
	public Page<Memo> findAllMemoToUser(Page<Memo> page, Long userId, List<PropertyFilter> filters) {
		return preHandlePage(memoDao.findPage(FIND_CURRENTUSER_MEMOS, page, filters, Memo.STATUS_1, userId));
	}
	
	/**
	 * 分页查询用户被共享的所有到期备忘录
	 * 
	 * @param page
	 * @param userId
	 * @param filters
	 */
	public List<Memo> findAllExpireMemoByUserId(Long userId) {
		return memoDao.find(FIND_EXPIRE_MEMO_BY_USERID, Memo.STATUS_1, MemoToUser.STATUS_1, userId);
	}
	
	/**
	 * 查询用户被共享的正在提醒中的备忘录
	 * 
	 */
	public List<Memo> findAllExpireMemoToUser() {
		return memoDao.find(FIND_MEMO_BY_STATUS, Memo.STATUS_1, MemoToUser.STATUS_1);
	}

	/**
	 * 修改备忘录提醒状态
	 * 
	 * @param mtuId
	 * @return 
	 */
	public MemoToUser updataMemoToUserStatusByMtuId(Long mtuId, String status) {
		// TODO Auto-generated method stub
		MemoToUser memoToUser = memoToUserDao.get(mtuId);
		memoToUser.setStatus(status);
		return memoToUser;
	}
	
	/**
	 * 判断时间大小HH:mm
	 * 前面的大于等于返回true；后面的大返回false
	 */
	public boolean ComparisonHHmm(String time1, String time2) {
		if(time1 != null && time2 != null) {
			String[] _time1 = time1.split(":");
			String[] _time2 = time2.split(":");
			if(Integer.parseInt(_time1[0]) > Integer.parseInt(_time2[0]) || (Integer.parseInt(_time1[0]) == Integer.parseInt(_time2[0]) && Integer.parseInt(_time1[1]) >= Integer.parseInt(_time2[1]))) {
				return true;
			} 
		}
		return false;
	}
	
	/**
	 * 根据提醒时间修改提醒状态
	 * 将到期的等待提醒修改为正在提醒
	 * 
	 */
	public void updataMemoToUserStatusByNow() {
		// TODO Auto-generated method stub
		List<Memo> memoList = memoDao.find(FIND_MEMO_BY_STATUS, Memo.STATUS_1, MemoToUser.STATUS_0);
		if(memoList != null) {
			Date date = new Date();
			SimpleDateFormat date1 = new SimpleDateFormat("HH:mm");
			SimpleDateFormat date2 = new SimpleDateFormat("EEE", Locale.ENGLISH);
			String week = new String();
			String week2 = date2.format(date);
			if(week2.equals("Mon")) {
				week = "1";
			} else if(week2.equals("Tus")) {
				week = "2";
			} else if(week2.equals("Wed")) {
				week = "3";
			} else if(week2.equals("Thu")) {
				week = "4";
			} else if(week2.equals("Fri")) {
				week = "5";
			} else if(week2.equals("Sat")) {
				week = "6";
			} else if(week2.equals("Sun")) {
				week = "7";
			}
			for(Memo memo : memoList) {
				if("每天同一时刻".equals(memo.getRemindType()) && date1.format(date).equals(memo.getRemindTime())) {
					updataMemoToUserStatusByMtuId(memo.getMtuId(), MemoToUser.STATUS_1);
					//推送发生变化的备忘录
					Comet.push(memo);//推送发生变化的备忘录
				} else if("每周提醒".equals(memo.getRemindType()) && memo.getRemindWeek() != null && memo.getRemindWeek().indexOf(week) >= 0 && date1.format(date).equals(memo.getRemindTime())) {
					updataMemoToUserStatusByMtuId(memo.getMtuId(), MemoToUser.STATUS_1);
					//推送发生变化的备忘录
					Comet.push(memo);;
				} else if("指定时刻".equals(memo.getRemindType()) && (date.getTime() > memo.getRemindDate().getTime() || (date.getTime() == memo.getRemindDate().getTime() && ComparisonHHmm(date1.format(date), memo.getRemindTime())))) {
					updataMemoToUserStatusByMtuId(memo.getMtuId(), MemoToUser.STATUS_1);
					//推送发生变化的备忘录
					Comet.push(memo);;
				}
			}
		}
	}

	/*
	 * 根据备忘录提醒时间修改清除备忘录之后，正在提醒状态变为过期提醒或等待提醒
	 * 
	 * @param mtuId
	 * */
	public MemoToUser updataMemoToUserStatusAfterRead(Long mtuId) {
		// TODO Auto-generated method stub
		MemoToUser memoToUser = memoToUserDao.get(mtuId);
		List<MemoToUser> memoToUserList = new ArrayList<MemoToUser>();
		if(memoToUser != null) {
			Memo memo = memoToUser.getMemo();
			if("指定时刻".equals(memo.getRemindType())) {
				memoToUser.setStatus(MemoToUser.STATUS_2);
			} else {
				memoToUser.setStatus(MemoToUser.STATUS_0);
			}
			memoToUserList.add(memoToUser);
		}
		return memoToUser;
	}

	public Memo findMemoByMtuId(Long mtuId) {
		// TODO Auto-generated method stub
		List<Memo> memoList = memoDao.find(FIND_MEMO_BY_MEMOTOUSERID, mtuId);
		if(memoList != null && !memoList.isEmpty()) {
			return preHandleObj(memoList.get(0));
		}
		return null;
	}

	/**
	 * 处理Page对象，翻译字段
	 * 
	 * @param page
	 * @return
	 */
	public Page<Memo> preHandlePage(Page<Memo> page) {
		List<Memo> list = page.getResult();
		if(list != null) {
			for(Memo n : list) {
				n.setCreateUserCaption(userDao.getUserNameById(n.getCreateUser()));
			}
		}
		return page;
	}
	
	/**
	 * 预处理对象，翻译字段
	 * 
	 * @param obj
	 * @return
	 */
	public Memo preHandleObj(Memo obj) {
		if(obj != null) {
			obj.setCreateUserCaption(userDao.getUserNameById(obj.getCreateUser()));
		}
		return obj;
	}
	
	
}
